package com.api.component;

import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.api.common.Common;
import com.api.model.pojo.Cache;

/**
 * 简单缓存
 * 
 * @author user
 *
 */
@Component
@Scope("singleton")
public class CacheComponent {
	@Autowired
	private MD5UtilComponent md5UtilComponent;

	private ConcurrentMap<String, Cache> map = new ConcurrentHashMap<String, Cache>();

	public boolean isExistsKey(String key) {
		return map.containsKey(key);
	}

	public String getCacheValue(String key) {
		String md5Key = md5UtilComponent.md5(key);
		if (map.containsKey(md5Key)) {
			Cache cache = map.get(md5Key);
			long nowTime = new Date().getTime();
			if (nowTime > (cache.getTime() + cache.getInvalidTime())) {
				// 超时
				return null;
			}
			return cache.getData();
		}
		return null;
	}

	public void setCacheToken(String md5Key, String token) {
		setCache(md5Key, Common.TOKEN_INVALID_TIME, token);
	}

	public void setCacheSmsCode(String md5Key, String smsCode) {
		setCache(md5Key, Common.SMSCODE_INVALID_TIME, smsCode);
	}

	private void setCache(String md5Key, long invalidTime, String data) {
		String key = md5UtilComponent.md5(md5Key);
		Cache cache = new Cache();
		cache.setKey(key);
		cache.setData(data);
		cache.setTime(new Date().getTime());
		cache.setInvalidTime(invalidTime);
		map.put(key, cache);
	}
}
